package demo1;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

//回显服务器
public class UdpEchoService {
    private  DatagramSocket socket = null;
    public UdpEchoService(int port) throws SocketException {
        socket = new DatagramSocket(port);//给服务器指定端口号
    }
    public void start() throws IOException {
        System.out.println("服务器启动！");
        while(true) {
            //1.接收请求并解析
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);//构造udp数据报
            socket.receive(requestPacket);//接收客户端的请求
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());//将二进制请求(udp数据报)转化成字符串(字符流)
            //2.计算响应
            String response = service(request);
            //3.返回响应
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),0,response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(responsePacket);
            System.out.printf("[%s:%d] req=%s,resp=%s\n",requestPacket.getAddress(),requestPacket.getPort(),request,response);
            //                                                 客户端ip          客户端端口号                  客户端请求     返回的响应
        }
    }
    public String service(String request) {
        return request;
    }
    public static void main(String[] args) throws IOException {
        UdpEchoService service = new UdpEchoService(1314);
        System.out.println("我是父类服务器");
        service.start();
    }

}
